#!/usr/bin/bash
# Usage
# You can override the configuration file location by simply setting PROFILES_FILE="your_location" before sourcing this shell script

function getWorkDirectory() {
    while read location in $test_locations; do
       if test -d "$location" && test -w "$location"; then
           echo "$location"
           return
       fi 
    done <<EOF
$PWD
/tmp
EOF
}


PROFILES_FILENAME="$( basename $0 .sh).conf"
WORK_PROFILE="$(getWorkDirectory)/$PROFILES_FILENAME.work"
PROFILES_FILE="${PROFILES_FILE-$PROFILES_FILENAME}"

function create_conf_file() {
    cat >"$PROFILES_FILE" <<EOF
# $( basename $0 ) configuration file
# Syntax: PROFILE/key=value
# You can use multiple profiles for each area
# For instance, you can have 3 profiles for sql variables, and 2 for a generic environment
EOF
    echo "Configuration file $PROFILES_FILE created."
    echo "Probably you may want to edit it before continuing, exiting..."
    type -t "$( basename $0)_create_conf_file" 2>&1 >/dev/null && $(basename $0)_create_conf_file "$PROFILES_FILE"
    exit 0
}

function doClean() {
    if [ -r "$WORK_PROFILE" ]; then rm "$WORK_PROFILE"; fi
}

function isValidProfile() {
    grep -q -e "^$1\/" "$PROFILES_FILE"
    return $?
}

function parseProfile() {
    grep -e "^$1\/" "$PROFILES_FILE" | sed "s/^$1\///g" >> "$WORK_PROFILE"
}

function list_profiles() {
    test "x$1" == "xnoheader" || echo "Profiles List"
    cat "$PROFILES_FILE" | grep -ve "^#" | grep "=" | sed "s/\/[a-zA-Z0-9\-\_]*=.*//g" | uniq
    exit 0 
}

function sourceProfiles() {
    source "$WORK_PROFILE"
}


function help_message() {
    if test "x$HELP_MESSAGE_MANAGED" == "xtrue"; then
	    doClean
	    exit 0
    fi
    if test "x$@" != "x"; then
        echo -e "$@\n"
    fi 
    app="$0"

    echo -e "Usages:\n\t$0 <profile1 profile2...>\t\tlist of profiles separated by spaces"
    echo -e "\t$0 list-profiles\t\t\tshows a list of available profiles from configuration file"
    echo -e "\t$0 create_conf\t\t\tcreates a template for the configuration file"
    echo -e "\t$0 --help\t\t\t\tthis help screen"
    doClean
    exit 0
}

if ! [ -r "$PROFILES_FILE" ] &&  test "x$1" != "xcreate_conf" ; then
    help_message "Configuration file "$PROFILES_FILE" not existing. Perhaps you want to create it?"    
fi
if test "x$1" == "x"; then
    help_message
fi


# echo "Using configuration file $PROFILES_FILE"

while test "x$1" != "x"; do
    case "$1" in
        "--help")
            help_message
	;;
	"create_conf")
            create_conf_file
        ;;
        "list-profiles")
            list_profiles
        ;;
	*)
	    if ! isValidProfile $1; then
                help_message "Profile $1 does not exist in configuration file $PROFILES_FILE"
            fi
         parseProfile "$1"
	;;
    esac
    shift
done

sourceProfiles
doClean

## Your Code here... or just "source" me ;-)

